package com.onion.orm.plugin.spring;

import com.onion.cache.annotation.EnableOnionCache;
import com.onion.orm.annotation.EnableEnhancedDao;
import com.onion.orm.config.EnhancedConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class OnionOrmRegistry implements ImportBeanDefinitionRegistrar {

    private Logger logger = LoggerFactory.getLogger(OnionOrmRegistry.class);

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importClassMeta,
                                        BeanDefinitionRegistry registry) {

        Map<String, Object> enableEnhancedDao = importClassMeta.getAnnotationAttributes(EnableEnhancedDao.class.getName());
        Object scanPath = enableEnhancedDao.get("scanPath");
        List<String> listPath = new ArrayList<>();
        if(scanPath == null){
            scanPath = new String[]{};
        }
        if(!(scanPath instanceof String[])){
            throw new RuntimeException("EnhancedDao扫描路径配置错误:" + scanPath);
        }
        for(String curPath : (String[])scanPath){
            listPath.add(curPath.trim());
        }
        EnhancedConfig enhancedConfig = new EnhancedConfig();
        enhancedConfig.setScanPath(listPath);
        BeanDefinitionBuilder factoryBuilder = BeanDefinitionBuilder.genericBeanDefinition(EnhancedDaoFactory.class);
        factoryBuilder.addConstructorArgValue(enhancedConfig);
        registry.registerBeanDefinition("enhancedDaoFactory", factoryBuilder.getBeanDefinition());
        logger.info("注册EnhancedDaoFactory:{}", factoryBuilder.getBeanDefinition().getBeanClassName());
    }

}